<template>
  <el-dialog
    v-model="visible"
    title="选择客户"
    width="800px"
    :close-on-click-modal="false"
    @close="handleClose"
  >
    <el-form :inline="true" @submit.prevent>
      <el-form-item label="客户编码">
        <el-input
          v-model="query.customerCode"
          clearable
          placeholder="支持模糊"
          @keyup.enter="handleSearch"
        />
      </el-form-item>
      <el-form-item label="客户名称">
        <el-input
          v-model="query.customerName"
          clearable
          placeholder="支持模糊"
          @keyup.enter="handleSearch"
        />
      </el-form-item>
      <el-form-item label="客户分类">
        <el-select
          v-model="query.categoryId"
          clearable
          filterable
          placeholder="请选择分类"
          style="width: 200px"
        >
          <el-option
            v-for="cat in categoryOptions"
            :key="cat.categoryId"
            :label="cat.categoryName"
            :value="String(cat.categoryId)"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" size="small" @click="handleSearch">查询</el-button>
        <el-button size="small" @click="handleReset">重置</el-button>
      </el-form-item>
    </el-form>

    <el-table
      v-loading="loading"
      :data="customerList"
      size="small"
      highlight-current-row
      @row-click="handleRowClick"
      @current-change="handleCurrentChange"
    >
      <el-table-column type="index" label="#" width="60" />
      <el-table-column prop="customerCode" label="客户编码" min-width="120" />
      <el-table-column prop="customerName" label="客户名称" min-width="180" />
      <el-table-column prop="customerType" label="客户类型" min-width="100">
        <template #default="{ row }">
          <el-tag v-if="row.customerType === 'ENTERPRISE'" type="primary">企业</el-tag>
          <el-tag v-else-if="row.customerType === 'INDIVIDUAL'" type="success">个人</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="phone" label="联系电话" min-width="120" />
      <el-table-column prop="email" label="邮箱" min-width="150" />
      <el-table-column prop="address" label="地址" min-width="200" show-overflow-tooltip />
      <el-table-column prop="status" label="状态" min-width="80" width="80">
        <template #default="{ row }">
          <el-tag v-if="row.status === 1" type="success">启用</el-tag>
          <el-tag v-else-if="row.status === 0" type="danger">停用</el-tag>
        </template>
      </el-table-column>
    </el-table>

    <div class="customer-selector__pagination">
      <el-pagination
        background
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="pageSize"
        :current-page="pageNum"
        @size-change="handleSizeChange"
        @current-change="handlePageChange"
      />
    </div>

    <template #footer>
      <div style="flex: 1; text-align: center">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" :disabled="!selectedCustomer" @click="handleConfirm">确定</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, watch, computed } from 'vue'
import { pageCustomer } from '@/api/crm/customer'
import { getCustomerCategoryTree } from '@/api/crm/customer'

interface CustomerInfo {
  customerId: string
  customerCode: string
  customerName: string
  customerType: string
  phone?: string
  email?: string
  address?: string
  status: number
}

interface Props {
  modelValue: boolean
}

interface Emits {
  (e: 'update:modelValue', visible: boolean): void
  (e: 'confirm', customer: CustomerInfo): void
}

const props = defineProps<Props>()
const emit = defineEmits<Emits>()

const visible = computed({
  get: () => props.modelValue,
  set: (val) => emit('update:modelValue', val)
})

const loading = ref(false)
const customerList = ref<CustomerInfo[]>([])
const total = ref(0)
const pageNum = ref(1)
const pageSize = ref(10)
const selectedCustomer = ref<CustomerInfo | null>(null)

const query = reactive<{
  customerCode?: string
  customerName?: string
  categoryId?: string
  status?: number
}>({
  customerCode: '',
  customerName: '',
  categoryId: '',
  status: 1 // 默认只显示启用的客户
})

const categoryOptions = ref<any[]>([])

// 加载客户分类
const loadCategories = async () => {
  try {
    const res = await getCustomerCategoryTree()
    // 将树形结构扁平化
    const flatten = (nodes: any[]): any[] => {
      let result: any[] = []
      nodes.forEach(node => {
        result.push(node)
        if (node.children && node.children.length > 0) {
          result = result.concat(flatten(node.children))
        }
      })
      return result
    }
    categoryOptions.value = flatten(res?.data || [])
  } catch (error) {
    console.error('加载客户分类失败:', error)
  }
}

// 加载客户列表
const loadCustomerList = async () => {
  loading.value = true
  try {
    const res = await pageCustomer({
      pageNum: pageNum.value,
      pageSize: pageSize.value,
      customerCode: query.customerCode || undefined,
      customerName: query.customerName || undefined,
      categoryId: query.categoryId || undefined,
      status: query.status
    })
    customerList.value = (res?.data?.records || []).map((item: any) => ({
      ...item,
      customerId: String(item.customerId)
    }))
    total.value = res?.data?.total || 0
  } catch (error) {
    console.error('加载客户列表失败:', error)
  } finally {
    loading.value = false
  }
}

const handleSearch = () => {
  pageNum.value = 1
  loadCustomerList()
}

const handleReset = () => {
  query.customerCode = ''
  query.customerName = ''
  query.categoryId = ''
  query.status = 1
  handleSearch()
}

const handlePageChange = (p: number) => {
  pageNum.value = p
  loadCustomerList()
}

const handleSizeChange = (s: number) => {
  pageSize.value = s
  pageNum.value = 1
  loadCustomerList()
}

const handleRowClick = (row: CustomerInfo) => {
  selectedCustomer.value = row
}

const handleCurrentChange = (row: CustomerInfo) => {
  selectedCustomer.value = row
}

const handleConfirm = () => {
  if (selectedCustomer.value) {
    emit('confirm', selectedCustomer.value)
    handleClose()
  }
}

const handleClose = () => {
  visible.value = false
  selectedCustomer.value = null
}

// 监听弹窗打开
watch(visible, (val) => {
  if (val) {
    loadCategories()
    loadCustomerList()
    selectedCustomer.value = null
  }
})
</script>

<style scoped lang="scss">
.customer-selector {
  &__pagination {
    margin-top: 12px;
    display: flex;
    justify-content: flex-end;
  }
}

:deep(.el-table__row) {
  cursor: pointer;
}

:deep(.el-table__row:hover) {
  background-color: var(--el-color-primary-light-9);
}
</style>

